import axios from 'axios'
import { Toast, Dialog } from 'vant'
import Store from '@/store'
import Router from '@/router'
const baseURL = `${Store.state.originURL}/zqt/api/`
class HttpRequest {
  constructor (baseUrl = baseURL) {
    this.baseUrl = baseUrl
    this.queue = {} // 队列
  }

  getInsideConfig () {
    const config = {
      baseURL: this.baseUrl,
      headers: {
        'Content-Type': 'application/json;charset=utf-8',
        'X-Requested-With': 'XMLHttpRequest',
        accept: 'application/json'
      }
      // transformRequest: [function (data) {
      //   // data = qs.stringify(data, { arrayFormat: 'indices', allowDots: true })
      //   return data
      // }]
    }
    return config
  }

  // 拦截器
  interceptors (instance, url) {
    // 请求拦截
    instance.interceptors.request.use(config => {
      if (!Object.keys(this.queue).length) {
        this.queue[url] = true
      }
      config.headers.token = Store.state.token || sessionStorage.getItem('token')
      return config
    }, error => {
      return Promise.reject(error)
    })
    // 响应拦截
    instance.interceptors.response.use(res => {
      delete this.queue[url]
      if (!Object.keys(this.queue).length) {
      }
      // 登录过期处理
      if (res.data.code === '40001') {
        Dialog.alert({
          message: res.data.msg
        }).then(() => {
          Router.push({
            path: '/',
            query: {
              loginAgain: true
            }
          })
        })
      } else if (res.data.code === '40002') {
      // code 失效
        window.location.href = window.location.pathname
      } else if (!requestIsOk(res.data)) {
        Toast({
          message: res.data.msg,
          type: 'fail',
          duration: 2 * 1000
        })
      }
      const data = res.data
      return data
    }, error => {
      delete this.queue[url]
      const message = error.message === 'Network Error' ? '网络异常，请稍后再试' : (error.message || error.msg)
      Toast({
        message,
        type: 'fail',
        duration: 5 * 1000
      })
      return Promise.reject(error)
    })
  }

  request (options) {
    const instance = axios.create()
    options = Object.assign(this.getInsideConfig(), options)
    this.interceptors(instance, options.url)
    return instance(options)
  }

  upLoaderImg (url, file) {
    // new 一个FormData格式的参数
    const params = new FormData()
    params.append('file', file)
    const config = {
      headers: { // 添加请求头
        'Content-Type': 'multipart/form-data'
      }
    }
    console.log('>>>>>>>>上传文件')
    config.headers.token = Store.state.token || sessionStorage.getItem('token')
    return new Promise((resolve, reject) => {
      // 把 uploadUrl 换成自己的 上传路径
      axios.post(baseURL + url, params, config).then(res => {
        // 如果为真 resolve出去
        if (res && res.data && res.data.status === 1) {
          resolve(res.data)
        } else {
          // 否则 Toast 提示
          Toast.fail(res.data && (res.data.msg))
          reject(res.data)
        }
      }).catch(err => {
        Toast.fail('系统异常')
        reject(err)
      })
    })
  }
}

export default function (options) {
  return new HttpRequest().request(options)
}

export function requestIsOk (res) {
  return res.success || (res && res.code === '0') || res.code === 0 || res.length
}

// export function setCookies (headers) {
//   console.log(headers)
//   if (headers.JSESSIONID) {
//     Cookies.setItem('JSESSIONID', headers.JSESSIONID)
//   }
// }
